<template>
  <div id="main">
    <el-form :inline="true" :model="queryData">
      <el-form-item label="采购日期">
        <el-date-picker @change="queryChange" clearable  v-model="queryData.date" type="date" placeholder="选择采购日期" style="width:150px"></el-date-picker>
      </el-form-item>
      <el-form-item label="是否过保">
        <el-select @change="queryChange" clearable  v-model="queryData.isOutOf" placeholder="是否过维保" style="width:150px">
          <el-option
            v-for="item in repairIsOutOfOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称" >
        <el-input v-model="queryData.name" style="width:150px" placeholder="请输入设备名称" @input="queryChange" clearable></el-input>
      </el-form-item>
      <el-form-item label="设备位置" >
        <el-input v-model="queryData.weizhi" style="width:150px" placeholder="请输入设备位置" @input="queryChange" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <!--<el-button type="primary" class="greenButton" @click="onQuery">查询</el-button>-->
        <el-button type="primary" class="greenButton" @click="reset()">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right;">
          <el-upload
              class="upload-idCardFile"
              action="http://hqgj.heweixiao.cn/import_equipment"
              :on-success="onsuccess"
              :on-error="onerror"
              :show-file-list="false">
              <el-button  type="primary">批量导入</el-button>
          </el-upload>
      </el-form-item>
      <el-form-item style="float:right;">
          <el-button type="primary" class="greenButton" @click="dleMany()">批量删除</el-button>
      </el-form-item>
    </el-form>

    <el-table
      border
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      style="width: 100%;border:1px solid #00BDAC;"
      height="78%"
      :data="equipmentList.slice((currentPage-1)*pagesize,currentPage*pagesize)"
      :header-cell-style="{borderRight:'none',backgroundColor:'#00BDAC',color:'#FFFFFF'}"
      
    >
      <el-table-column
      type="selection"
      width="55">
      </el-table-column>
      <el-table-column align="center" type="index" :index="table_index" label="序号" width="50px"></el-table-column>
      <el-table-column align="center" prop="date" label="采购日期" width="150px"></el-table-column>
      <el-table-column align="center" prop="order" label="设备编号"></el-table-column>
      <el-table-column align="center" prop="name" label="设备名称"></el-table-column>
      <el-table-column align="center" prop="weizhi" label="设备位置">
        <template slot-scope="scope">
          <div v-if="scope.row.weizhi==0">
            
          </div>
          <div  v-if="scope.row.weizhi!=0">
            {{scope.row.weizhi}}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="isOutOf" width="50px" label="是否过保"></el-table-column>
      <el-table-column align="center" prop="img" label="设备图片">
        <template slot-scope="scope">
          <el-image v-show="scope.row.img&&scope.row.img!='null'" :src="scope.row.img" style="width: 50px;height: 50px;" :preview-src-list="imglist" @click="chakan(scope.row.img)"></el-image>
          <div v-show="!scope.row.img||scope.row.img=='null'">
            
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="detail" width="250px" label="管理">
        <template slot-scope="scope">
          <el-button
            size="mini"
            class="greenButton"
            @click="handleChangeLocation(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            class="pinkButton"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="footer">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="pagesize"
        layout="total, prev, pager, next, jumper"
        :total="equipmentList.length"
        prev-text="上一页"
        next-text="下一页"
      ></el-pagination>
      <div>
        <el-button
              size="middle"
              @click="daochu()"
              class="greenButton dachu"
            >导出/下载</el-button>
            <el-button
              size="middle"
              type="primary"
              @click="downloadTemplate()"
              class="dachu"
            >模板下载</el-button>
      </div>
    </div>

    <el-dialog
      :visible.sync="isShowDispatch"
      destroy-on-close
      :show-close="false"
      @close="isShowDispatchClose"
      class="edit-dialog"
      width="1100px"
    >
      <div slot="title" class="edit-dialog-title">修改设备位置</div>
      <el-form class="edit-form" label-width="100px">
        <el-form-item label="设备编号：">
          <el-input v-model="editFormData.order" class="list-input" placeholder></el-input>
        </el-form-item>
        <el-form-item label="设备名称：">
          <el-input v-model="editFormData.name" class="list-input" placeholder></el-input>
        </el-form-item>
        <el-form-item label="设备图片：">
         <el-upload
            action="http://hqgj.heweixiao.cn/base64_upload"
            list-type="picture-card"
            :on-success="handelupdata"
            :limit="1"
            :file-list="fileList"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
          <span>最多上传一张图片</span>
        </el-form-item>
        <el-form-item label="设备位置：" style="width: 800px;">
          <el-select @change="gaibian" v-model="editFormData.louvalue" placeholder="请选择楼">
             <el-option
               v-for="item in options"
               :key="item.id"
               :label="item.f_name"
               :value="item.id"
               :disabled="item.disabled">
             </el-option>
          </el-select>
          <el-select v-model="editFormData.cengvalue" placeholder="请选择层">
             <el-option
               v-for="item in options1"
               :key="item.id"
               :label="item.f_name"
               :value="item.id"
               :disabled="item.disabled">
             </el-option>
          </el-select>
          <el-input
            placeholder="请输入房间号"
            v-model="editFormData.rongvalue"
            style="width:200px;"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="质保时间：">
          <el-date-picker
            v-model="editFormData.timeRange"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="目前状态：">
          <el-select class="list-input" v-model="editFormData.status">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="cancel" class="pinkButton" type="primary">取消</el-button>
        <el-button @click="submit" class="greenButton" type="primary">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import DayJs from 'dayjs';
let pageObj={
  page:1,
  pageSize: 10
};
let originList = [];
export default {
  data: function() {
    return {
      imglist:['https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg'],
      value1:"",
      dialogImageUrl: '',
      dialogVisible: false,
      fileList:[],
      queryData: {
        isOutOf: "",
        name: "",
        date: "",
        weizhi:''
      },

      repairIsOutOfOptions: [
        {
          value: "",
          label: "全部"
        },
        {
          value: "是",
          label: "是"
        },
        {
          value: "否",
          label: "否"
        }
        
      ],

      nameOptions: [
        {
          value: "",
          label: "全部"
        },
        {
          value: "打印机",
          label: "打印机"
        },
        {
          value: "台式电脑",
          label: "台式电脑"
        }
      ],

      equipmentList: [
        /*{
          date: "12.8",
          order: "000001",
          name: "打印机",
          location: "1号楼5层103",
          isOutOf: "否",
          description: "打印机需要加墨,派厂家来加原 装墨",
          orderStatus: "已处理"
        },
        {
          date: "12.8",
          order: "000001",
          name: "打印机",
          location: "1号楼5层103",
          isOutOf: "否",
          description: "打印机需要加墨,派厂家来加原 装墨",
          orderStatus: "已处理"
        },
        {
          date: "12.8",
          order: "000001",
          name: "打印机",
          location: "1号楼5层103",
          isOutOf: "否",
          description: "打印机需要加墨,派厂家来加原 装墨",
          orderStatus: "已处理"
        },
        {
          date: "12.8",
          order: "000001",
          name: "打印机",
          location: "1号楼5层103",
          isOutOf: "否",
          description: "打印机需要加墨,派厂家来加原 装墨",
          orderStatus: "已处理"
        },
        {
          date: "12.8",
          order: "000001",
          name: "打印机",
          location: "1号楼5层103",
          isOutOf: "否",
          description: "打印机需要加墨,派厂家来加原 装墨",
          orderStatus: "已处理"
        },*/
      ],

      currentPage: 1,
      pagesize:10,
      isShowDetail: false,

      detailTable: [
        {
          person: "张三",
          route: "1号线",
          pointOne: "1号楼 正常签到",
          pointTwo: "2号楼 正常签到",
          pointThree: "3号楼 正常签到",
          status: "正常"
        }
      ],

      isShowDispatch: false,

      editFormData: {
        order: "",
        name: "",
        louvalue:"",
        cengvalue:"",
        rongvalue:"",
        imglist:"",
        timeRange: "",
        status: ""
      },
      

      statusOptions: [
        {
          value: "1",
          label: "正常使用"
        },
        {
          value: "2",
          label: "已报废"
        }
      ],
      options:[],
      options1:[],
      fullscreenLoading: false, // 加载中
      imFile: '', // 导入文件el
      outFile: '',  // 导出文件el
      errorDialog: false, // 错误信息弹窗
      errorMsg: '', // 错误信息内容
      multipleSelection:[],
    };
  },
  created(){
    this.getList()
  },
  mounted(){
    this.imFile = document.getElementById('imFile')


     this.huoqu();
  },
  methods: {
    downloadTemplate(){
      console.log('模板下载')
      window.location.href = "http://hqgj.heweixiao.cn/down_equipmentExcel"
    },
    isShowDispatchClose(){
      console.log('对话框关闭')
      this.editFormData={
        order: "",
        name: "",
        louvalue:"",
        cengvalue:"",
        rongvalue:"",
        imglist:"",
        timeRange: "",
        status: ""
      }
      this.fileList = []
    },
    daochu(){
      window.location.href = "http://hqgj.heweixiao.cn/export_equipment"
    },
    dleMany(){
      console.log(this.multipleSelection)
      if(this.multipleSelection.length==0){
        return this.$message.error('请选择您要删除的信息')
      }
      const arr = []
      this.multipleSelection.forEach((item)=>{
          arr.push(item.id)
      })
      console.log(arr.join(','))
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let parme = {
                id:arr.join(',')
              }
              console.log(parme)
              this.ajaxCommon.ajax({
                    url: 'piliangequipmentdelete',
                    data:parme,
                    success: (res) => {
                      console.log(res)
                      if(res.code == 200){
                        this.$message({
                            message: '删除成功',
                            type: 'success',
                            duration:'1000'
                          });
                          this.getList()
                      }else{
                        this.$message({
                            message: res.status,
                            type: 'error',
                            duration:'2000'
                          });

                      }
                     
                    }
                });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
    },
    handleSelectionChange(selection){
        console.log(selection)
        this.multipleSelection = selection
    },
    onerror(file, fileList){
      console.log('导入失败',file)
    },
    onsuccess(file, fileList){
      console.log('导入成功',file)
      if(file.code==200){
        this.getList()
        return this.$message.success(file.status)
      }else{
        return this.$message.error(file.status)
      }
    },
    reset(){
      this.queryData.date = ''
      this.queryData.isOutOf = ''
      this.queryData.name = ''
      this.queryData.weizhi = ''
      this.queryChange()
    },
    table_index(index){
        return (this.currentPage -1) * this.pagesize + index + 1
    },  

    chakan(img){
      this.imglist[0] = img;
    },
    huoqu(){
      this.ajaxCommon.ajax({
          url: 'louceng',
          success: (res)=>{
             console.log(res);
             if(res.code == 200){
               this.options = res.data;
             }
          }
        });

    },
    handleRemove(file, fileList) {
        this.editFormData.imglist = '';
      },
    handelupdata(response, file, fileList){
      console.log(this.dialogImageUrl)
      console.log(response, file, fileList);
        this.editFormData.imglist = response;
    },
    gaibian(){
      console.log(typeof(this.editFormData.louvalue))
      this.options.forEach(item => {
        if(this.editFormData.louvalue == item.id){
          this.options1 = item.floor;
        }
      })
      this.editFormData.cengvalue = ''
      this.editFormData.rongvalue = ''
    },
    gaibian1(){
      console.log(typeof(this.editFormData.louvalue))
      this.options.forEach(item => {
        if(this.editFormData.louvalue == item.id){
          this.options1 = item.floor;
        }
      })
        
    },
    queryChange(){
      console.log(this.queryData)
      var query = {};
      if(this.queryData.date){
        query.date = DayJs(this.queryData.date).format('YYYY-MM-DD');
      }
      if(this.queryData.isOutOf){
        query.isOutOf = this.queryData.isOutOf;
      }
      if(this.queryData.name){
        query.name = this.queryData.name;
      }
      if(this.queryData.weizhi){
        query.weizhi  = this.queryData.weizhi;

      }
      var keys = Object.keys(query);
      console.log('keys',keys)
      var list = [];
      if(keys.length){
        console.log(1)
        originList.forEach(item=>{
          var mnust = 0;
          for(var i=0;i<keys.length;i++){
            var key = keys[i];
            console.log('key',key)
            if(item[key].indexOf(query[key])>=0){
              mnust++;
            }
          }
          if(mnust == keys.length){
            list.push(Object.assign({},item));
          }

        })
      } else {
        originList.forEach(item=>{
          list.push(Object.assign({},item));
        })
      }
      this.equipmentList = list;
    },
    filterList(){

    },
    getList(){
      this.ajaxCommon.ajax({
        url: 'equipmentList',
        success: (res) => {
          var list = [];
          originList = [];
          console.log('--------------',res.data)

          res.data.forEach((item)=>{
            var img = item.eq_img;
            var iT = {
              id: item.eq_id,
              // date: DayJs(item.eq_purchase_time).format('YYYY-MM-DD'),
              date:item.eq_purchase_time,
              order: item.eq_model,
              name: item.eq_name,
              img: img,
              weizhi:item.eq_building_id1+item.eq_floor_id1+item.eq_room,
              louvalue:item.eq_building_id,
              cengvalue:item.eq_floor_id,
              rongvalue:item.eq_room,
              isOutOf: item.s,
              status: item.eq_state+'',
              timeRange: item.eq_main_time,
              description: "",
              orderStatus: ""
            };
            list.push(iT);
            originList.push(Object.assign({}, iT));
          });
          console.log(JSON.stringify(list));
          this.equipmentList = list;
          setTimeout(()=>{
            console.log(this.equipmentList)
          },2000)
        }
      });
    },

    onQuery() {
      console.log(this.queryData);
    },
    onDetailclick(row) {
      this.isShowDetail = true;
      console.log(row);
    },
    handleRemind(row) {
      console.log(row);
    },
    handleChangeLocation(index, row) {
      this.fileList = []
      console.log(index,row)
      //  设备状态1正常使用  2-维修 3-养护  -1已报废     2 只能为正常和报废        3只能为正常和报废
      // 质保时间改成可编辑 1和-1
      if(row.status==2){
        this.editFormData.status = 2
        this.statusOptions= [
              {
                value: "2",
                label: "维修"
              },
              {
                value: "1",
                label: "正常使用"
              },
              {
                value: "-1",
                label: "已报废"
              }
          ]
      }
      if(row.status==3){
        this.editFormData.status = 3
        this.statusOptions= [
              {
                value: "3",
                label: "养护"
              },
              {
                value: "1",
                label: "正常使用"
              },
              {
                value: "-1",
                label: "已报废"
              }
          ]
      }
      if(row.status==1){
        this.editFormData.status = 1
        this.statusOptions= [
              {
                value: "1",
                label: "正常使用"
              },
              {
                value: "-1",
                label: "已报废"
              }
          ]
      }
      if(row.status==-1){
        this.editFormData.status = -1
        this.statusOptions= [
              {
                value: "1",
                label: "正常使用"
              },
              {
                value: "-1",
                label: "已报废"
              }
          ]
      }
      this.isShowDispatch = true;
      // console.log(row)
      // var times = null;
      // try {
      //   let temp = JSON.parse(row.timeRange);
      //   if(Array.isArray(temp)){
      //     times = [];
      //     temp.forEach(item=>{
      //       times.push(new Date(item));
      //     })
      //   }
      // }catch (e) {

      // }
      console.log(row)
      if(row.img){
        let arr = [];
        arr.push({url:row.img});
        this.fileList = arr;
      }else{
        this.fileList = [];
      }
      
      this.editFormData = {
        id: row.id,
        order: row.order,
        name: row.name,
        louvalue:row.louvalue,
        cengvalue:row.cengvalue,
        rongvalue:row.rongvalue,
        imglist:row.img,
        status: row.status + '',
        timeRange: row.timeRange
      }
      console.log(this.editFormData)
      this.gaibian1();
      /*editFormData: {
        order: "",
        name: "",
        location: "",
        timeRange: [],
        status: ""
      },
      id: item.eq_id,
      date: item.eq_purchase_time,
      order: item.eq_model,
      name: item.eq_name,
      img: img,
      location: item.eq_useaddress,
      isOutOf: item.eq_state==1?"否":"是",
      status: item.eq_state,
      timeRange: item.eq_main_time,
      description: "",
      orderStatus: ""

      */

    },
    handleCancel(row) {
      console.log(row);
    },
    //分页
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleDelete(index, row) {
      console.log(row);
      var id = row.id;
      this.$confirm('删除设备后不可恢复，确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ajaxCommon.ajax({
          url: 'equipmentDel',
          urlConcat: id,
          success: (res)=>{
            if(res.code==200){
              var list = this.equipmentList;
              for(var i=0;i<list.length;i++){
                if(list[i].id==id){
                  list.splice(i,1);
                  break;
                }
              }
              this.equipmentList = list;
              this.$message({
                            message: '删除成功',
                            type: 'success',
                            duration:'1000'
                          });
            } else {
              this.ajaxCommon.notice(res.status,3);
            }
          }
        });
      })
    },
    submit(){
      let temp = this.editFormData;
      var uuid=localStorage.getItem('uid');
      console.log('提交数据',temp)
      // var date = new Date(time)
      var time1 = temp.timeRange
      var date = new Date(time1)
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      var D = date.getDate()<10?'0' + date.getDate():date.getDate()
      var current = Y + M + D 
      let data = {
        eq_model: temp.order,
        eq_name: temp.name,
        eq_building_id:temp.louvalue,
        eq_floor_id:temp.cengvalue,
        eq_room:temp.rongvalue,
        eq_img:temp.imglist,
        eq_main_time: current,
        eq_state: temp.status,
        uid: uuid
      };
      console.log('修改--------',data)
      let formData = new FormData();
      Object.keys(data).forEach(key=>{
        formData.append(key, data[key]);
      });
      this.$confirm('确认修改设备信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.ajaxCommon.ajax({
          url: 'equipmentEdit',
          headers:{'Content-Type': 'multipart/form-data'},
          method: 'post',
          urlConcat: temp.id,
          data: formData,
          success: (res)=>{
            if(res.code==200){
              this.getList();
              this.ajaxCommon.notice('修改成功');
              this.isShowDispatch = false;
              // this.editFormData={
              //       order: "",
              //       name: "",
              //       louvalue:"",
              //       cengvalue:"",
              //       rongvalue:"",
              //       imglist:"",
              //       timeRange: "",
              //       status: ""
              //     }
              this.fileList = []
            } else {
              this.ajaxCommon.notice(res.status,3);
            }
          }
        });
      });
    },
    cancel(){
      this.isShowDispatch = false;
    }
  }
};
</script>

<style lang="less" scoped>

#main {
  width: 100%;
}

a {
  color: #00bdac;
  text-decoration: none;
}

.footer {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.edit-dialog-title {
  color: #ffffff;
  padding-left: 30px;
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  background: #00bdac;
}

.edit-form {
  width: 530px;
}

.message-button {
  text-align: right;
}

.list-input{
  width: 400px;
}
</style>

<style lang="less">
.detail-dialog {
  .el-dialog__header {
    padding: 0;
  }

  .el-dialog__body {
    padding: 0;
    height: 410px;
  }
}

.edit-dialog {
  .el-dialog__header {
    padding: 0;
  }
}
</style>
